<template>
  <div class="proceeDetail">
    <div>
      <jc-button
        :btn-arr="['reload', 'copy', 'voucher', 'save', 'sub', 'option', 'remove', 'pass', 'list']"
        :disab-arr="[isDisabled && 'save', 'close', 'cancel', 'copy', 'com1', 'com2', 'using', 'freeze', 'toExcel']"
        :fbillno="subDetails.fbillno"
        :list="'/proceedList'"
        @refresh="paymentDetails"
        @save="newlyAdjustment"
        @submit="newlyAdjustment(1)"
        @noSubmit="submit(2)"
        @audit="audit(1)"
        @noAudit="audit(2)"
        @del="remove"
        @copyDa="copyProcee"
        @voucher="voucherVis=true"
        @voucherLok="LooktialsTask"
      />
    </div>
    <el-tabs v-model="activeName" @tab-click="handleOther">
      <el-tab-pane :label="$t('market.info')" name="first">
        <el-form :model="subDetails" label-width="100px" size="mini">
          <el-form-item :label="$t('market.state')">
            <el-tag :type="subDetails.stateColor">{{ subDetails.fdocumentstatus }}</el-tag>
          </el-form-item>
          <el-form-item :label="$t('market.billNo')">
            <el-input
              v-model="subDetails.fbillno"
              disabled
            />
          </el-form-item>
          <el-form-item :label="$t('market.billType')">
            <el-input
              v-model="subDetails.fbillTypeName"
              disabled
            />
          </el-form-item>
          <el-form-item :label="$t('market.tafName')">
            <el-input
              v-model="subDetails.ftafName"
              disabled
            />
          </el-form-item>
          <el-form-item :label="$t('market.comeGounit')">
            <!--  供应商  -->
            <el-input
              v-if="subDetails.ftafId===1251"
              v-model="subDetails.fsupplierName"
              disabled
            />
            <!--            客户-->
            <el-input
              v-if="subDetails.ftafId===1252"
              v-model.trim="subDetails.fcustName"
              disabled
            />
            <!--           部门 -->
            <el-input
              v-if="subDetails.ftafId===1253"
              v-model="subDetails.fdeptName"
              disabled
              size="mini"
            />
            <!--            员工-->
            <el-input
              v-if="subDetails.ftafId===1254"
              v-model="subDetails.fstaffName"
              disabled
              size="mini"
            />
          </el-form-item>
          <el-form-item :label="$t('market.businessDate')">
            <el-date-picker
              v-model.trim="subDetails.fdate"
              type="date"
              value-format="yyyy-MM-dd"
              style="width: 152px"
              :disabled="isDisabled"
            />
          </el-form-item>
          <el-form-item :label="$t('market.endData')">
            <el-date-picker
              v-model.trim="subDetails.fenddate"
              type="date"
              value-format="yyyy-MM-dd"
              style="width: 152px"
              :disabled="isDisabled"
            />
          </el-form-item>
          <el-form-item :label="$t('market.settleCurr')">
            <el-input v-model="subDetails.fcurrencyName" :disabled="isDisabled">
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="openCurrency = true"
              />
            </el-input>
          </el-form-item>
          <el-form-item :label="$t('market.saler')">
            <el-input
              v-model="subDetails.fsalerName"
              disabled
            />
          </el-form-item>
          <!--          <el-form-item label="收款组织">-->
          <!--            <el-input v-model.trim="subDetails.orgColName" disabled />-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="结算组织">-->
          <!--            <el-input v-model.trim="subDetails.orgSetName" disabled />-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="销售组织">-->
          <!--            <el-input v-model.trim="subDetails.orgSalName" disabled />-->
          <!--          </el-form-item>-->
        </el-form>
      </el-tab-pane>
      <el-tab-pane :label="$t('market.fince')" name="two">
        <el-form :model="subDetails" label-width="100px" size="mini">
          <el-form-item :label="$t('market.exchangeType')">
            <el-input v-model.trim="subDetails.fexchangetype" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.localCurr')">
            <el-input v-model.trim="subDetails.flocalCurr" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.exchangeRate')">
            <el-input v-model.trim="subDetails.fexchangerate" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.shouldamount1')">
            <el-input v-model.trim="subDetails.fshouldamount" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.shouldamount_lc1')" label-width="110px">
            <el-input v-model.trim="subDetails.fshouldamountLc" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.realamount1')">
            <el-input v-model.trim="subDetails.frealamount" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.realamount_lc1')" label-width="110px">
            <el-input v-model.trim="subDetails.frealamountLc" disabled />
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane :label="$t('market.other')" name="log">
        <jc-marker
          ref="log"
          :fnumber="subDetails.fbillno"
          other-height="65vh"
          :other-url-object="otherUrlObject"
        />
      </el-tab-pane>
    </el-tabs>
    <div v-show="activeName!=='log'" class="table-content">
      <div style="margin-bottom: 5px;">
        <el-button size="mini" @click="newHang">{{ $t('btn.newHang') }}<!--新增行--></el-button>
        <el-button size="mini" @click="delHang">{{ $t('btn.delHang') }}<!--删除行--></el-button>
        <el-button size="mini" @click="batchFill">{{ $t('btn.batchFill') }}<!--批量填充--></el-button>
      </div>
      <jc-table
        :table-data="tableData"
        :table-header="tableHeader"
        :table-height="tableHeight"
        serial
        :get-summaries="getSummaries"
        show-summary
        @cellClick="cellClick"
        @rowClick="rowClick"
      >
        <!--    结算方式  -->
        <template v-slot:btnState="col">
          <el-select
            v-model="col.scope.row.fpaymenttypeId"
            size="mini"
            :disabled="isDisabled"
          >
            <el-option
              v-for="item in paymentDa"
              :key="item.fid"
              :label="item.fname"
              :value="item.fid"
            />
          </el-select>
        </template>
        <!--    收款用途  -->
        <template v-slot:btnStates="col">
          <el-select
            v-model="col.scope.row.freasonId"
            size="mini"
            :disabled="isDisabled"
          >
            <el-option
              v-for="item in reasonDa"
              :key="item.fid"
              :label="item.fname"
              :value="item.fid"
            />
          </el-select>
        </template>
        <!--        应付金额-->
        <template v-slot:tagSlot="col">
          <el-input-number v-model="col.scope.row.fshouldamount" :precision="2" :disabled="isDisabled" :min="0" @change="handelMount(col.scope.$index)" />
        </template>
        <!--        手续费-->
        <template v-slot:billSlot="col">
          <el-input-number v-model="col.scope.row.fchargeamount" :precision="4" :disabled="isDisabled" :min="0" @change="handelMount(col.scope.$index)" />
        </template>
        <!--        备注-->
        <template v-slot:btnSlot="col">
          <el-input v-model="col.scope.row.fremark" :disabled="isDisabled" />
        </template>
        <!--       我方银行账号-->
        <template v-slot:orderSlot="col">
          <el-input v-model="col.scope.row.fbankcode" :disabled="isDisabled">
            <i
              slot="suffix"
              class="el-input__icon el-icon-search"
              @click="bankShow(col.scope.$index)"
            />
          </el-input>
        </template>
      </jc-table>
      <!--币别-->
      <currency v-if="openCurrency" @currency="currencySelectRow" />
      <!--银行账号-->
      <bank v-if="bankVisiblit" @client="bankData" />
      <voucherPopup v-if="voucherVis" :enum-id="24" @voucher="credentialsTask" />

    </div>
  </div>
</template>

<script>
import {
  createBillVoucherTask,
  delReceipts,
  notreviewReceipts,
  notsubmitReceipts,
  queryReceiptDetails,
  reviewReceipts,
  submitReceipts,
  updateReceipt
} from '@/api/financial/cashier'
import { queryRate, queryViewItem } from '@/api/marketManage/marketOrder'
import autocomplete from '@/views/market/marketManage/createMarkerOrder/components/autocomplete'
import jcButton from '@/components/Button'
import { notoMxBmina, toMxBmina } from '@/components/ToMxamineState'
import jcMarker from '@/components/marker'
import billFa from '@/views/financial/cashier/mixins'
import bility from '@/mixin/Operability'
import jumpMateriel from '@/components/JumpMateriel'

export default {
  name: 'PaymentDetail',
  components: {
    currency: () => import('@/views/market/marketManage/createMarkerOrder/components/currency'),
    voucherPopup: () => import('@/views/financial/cashier/receivable/components/voucherPopup'),
    bank: () => import('@/views/financial/cashier/payment/component/bank'),
    jcMarker,
    jcButton
  },
  mixins: [jumpMateriel, autocomplete, billFa, bility],
  data() {
    return {
      paymentDa: [],
      reasonDa: [],
      openCurrency: false, // 币别弹窗
      voucherVis: false, // 凭证弹窗
      bankVisiblit: false, // 账户弹窗
      staffType: 2, // 采购员
      subDetails: {},
      activeName: 'first',
      indexSelf: 0,
      otherUrlObject: {},
      // 表头
      tableData: [], // 应付单数据
      tableHeight: '70vh',
      tableHeader: [
        { label: this.$t('market.settleType'), type: 'state', prop: 'fpaymenttypeId', width: '120' },
        { label: this.$t('market.receipt'), type: 'states', prop: 'freasonId', width: '120' },
        { label: this.$t('market.shouldamount1'), type: 'tag', prop: 'fshouldamount', width: '80' },
        { label: this.$t('market.chargeamount'), type: 'bill', prop: 'fchargeamount', width: '80' },
        { label: this.$t('market.realamount1'), prop: 'frealamount', width: '80' },
        { label: this.$t('market.note'), type: 'btn', prop: 'fremark' },
        { label: this.$t('market.ourBankcode'), type: 'order', prop: 'fbankcode', width: '200' },
        { label: this.$t('market.fmaterial'), prop: 'fnumber', width: '120' },
        { label: this.$t('shop.fname2'), prop: 'fname' },
        { label: this.$t('market.fdescripTion'), prop: 'fdescription', minWidth: '150' },
        { label: this.$t('market.purOrderNo'), prop: 'fpurfbillno' },
        { label: this.$t('market.paezText1'), prop: 'salKhddh' }
      ],
      isDisabled: false,
      delArr: []
    }
  },
  created() {
    this.queryTBasBilltype2() // 结算方式ID(SX_SETTLETYPE)
    this.queryTBasBilltype3() // 收款用途ID(SX_PURPOSEPAYMENT)
    if (this.$route.params.id) {
      this.paymentDetails()
    }
    this.tableHeight = window.innerWidth > 1440 ? 'calc(100vh - 230px)' : '73vh'
  },
  methods: {
    // 详情
    paymentDetails() {
      const fid = this.$route.params.id
      queryReceiptDetails({ fid }).then(res => {
        if (res.code === 0) {
          this.subDetails = toMxBmina(res.data)
          this.otherUrlObject = res.data
          this.tableData = res.data.details
          this.isDisabled = this.subDetails.fdocumentstatus === this.$t('market.state2') || this.subDetails.fdocumentstatus === this.$t('market.state1')
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 保存
    newlyAdjustment(ev) {
      const DATA = {
        ...notoMxBmina(this.subDetails),
        details: this.tableData,
        delArr: this.delArr
      }
      updateReceipt(DATA).then(res => {
        if (res.code === 0) {
          this.delArr = []
          ev === 1 ? this.submit(1) : this.paymentDetails()
          this.$message({ showClose: true, message: res.message, type: 'success' })
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 计算实付金额
    handelMount(index) {
      const item = this.tableData[index]
      item.frealamount = item.fshouldamount + item.fchargeamount
      this.subDetails.fshouldamount = 0
      this.subDetails.frealamount = 0
      this.tableData.forEach(res => {
        this.subDetails.fshouldamount += res.fshouldamount * 1
        this.subDetails.frealamount += res.frealamount * 1
      })
      const fexchangerate = this.subDetails.fexchangerate
      this.subDetails.fshouldamountLc = (this.subDetails.fshouldamount * fexchangerate).toFixed(2)
      this.subDetails.frealamountLc = (this.subDetails.frealamount * fexchangerate).toFixed(2)
    },
    // 币别选中
    currencySelectRow(item) {
      if (item.fsettleCurrId || item.fcurrencyId) {
        this.subDetails.fsettlecurrId = item.fsettleCurrId || item.fcurrencyId
        this.subDetails.fcurrencyName = item.fsettleCurrIdName || item.fname
        this.querySalerRate()
      }
      this.openCurrency = false
    },
    // 查询汇率
    async querySalerRate() {
      const DATA = {
        fromcurrId: this.subDetails.flocalcurrId,
        tocurrId: this.subDetails.fsettlecurrId,
        queryDate: this.subDetails.fdate
      }
      const { data: RES, code, message } = await queryRate(DATA)
      if (code === 0) {
        this.subDetails.fexchangerate = RES.exchangeRate
        this.subDetails.fsettletypeName = RES.exchangeTypeName
        this.subDetails.fexchangetypeId = RES.exchangeTypeId
      } else {
        this.subDetails.fexchangerate = ''
        this.$confirm(message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
      }
    },
    // 银行弹窗
    bankShow(index) {
      this.indexSelf = index
      this.bankVisiblit = true
    },
    bankData(ev) {
      if (ev.fbankaccountId) {
        const item = this.tableData[this.indexSelf]
        item.fbankcodeId = ev.fbankaccountId
        item.fbankcode = ev.faccount
      }
      this.bankVisiblit = false
    },
    // 查询结算方式
    async queryTBasBilltype2() {
      const { data: RES } = await queryViewItem({ viewName: 'SX_SETTLETYPE' })
      this.paymentDa = RES.list
    },
    // 查询收款用途
    async queryTBasBilltype3() {
      const { data: RES } = await queryViewItem({ viewName: 'SX_PURPOSERECEIPT' })
      this.reasonDa = RES.list
    },
    // 公共函数
    toExamineFun(api) {
      const DATA = { Numbers: [this.subDetails.fbillno] }
      api(DATA).then(res => {
        if (res.code !== 0) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.paymentDetails()
        this.innerHTM = ''
        res.data.forEach(res => {
          this.innerHTM += '<div>' + res + '</div>'
        })
        this.$notify.warning({
          title: '提示',
          message: this.innerHTM,
          duration: 3000, offset: 50,
          dangerouslyUseHTMLString: true
        })
      })
    },
    // 提交
    submit(ev) {
      const api = ev === 1 ? submitReceipts : notsubmitReceipts
      this.toExamineFun(api)
    },
    // 审核
    audit(ev) {
      const api = ev === 1 ? reviewReceipts : notreviewReceipts
      this.toExamineFun(api)
    },
    // 删除
    remove() {
      this.$confirm('确定要删除该订单么？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const api = delReceipts
        const DATA = { Numbers: [this.subDetails.fbillno] }
        api(DATA).then(res => {
          if (res.code !== 0) {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
            return
          }
          // 关闭当前页面
          this.$store.dispatch('tagsView/guanbi', this.$route)
          this.$router.push({ path: '/proceedList' })
        })
      })
    },
    // 凭证生成
    credentialsTask(ev) {
      this.voucherVis = false
      if (!ev) return
      const { fperiod, fgenerate, fmatching } = ev
      const DATA = {
        fids: [this.subDetails.fid],
        fgenerate, fmatching, fperiod,
        fsettlecurrId: [this.subDetails.fsettlecurrId],
        fdate: [this.subDetails.fdate],
        fexchangerates: [this.subDetails.fexchangerate + ''],
        enumId: 24, // 收款单
        mouldId: 60
      }
      createBillVoucherTask(DATA).then(res => {
        if (res.code === 0) {
          this.$message({ showClose: true, message: res.message, type: 'success' })
          this.$router.push({ path: '/certificate' })
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 查看凭证
    LooktialsTask() {
      const id = this.subDetails.voucherid
      if (id) {
        this.$router.push({ path: `/certificateDetail/${id}` })
      } else {
        this.$confirm('该单据未能查询到对应的业务凭证！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
      }
    },
    // 复制
    copyProcee() {
      this.$router.push({
        path: '/createProceed',
        query: {
          id: this.subDetails.fid
        }
      })
    },
    handleOther(tab) {
      if (tab.name === 'log') {
        this.$refs.log.otherlog()
      }
    },
    // 单击行
    rowClick(row) {
      this.indexSelf = row.index
    },
    // 新增行
    newHang() {
      this.tableData.push({
        fpaymenttypeId: '', freasonId: '', fshouldamount: 0, fchargeamount: 0, frealamount: 0,
        fbankcode: '', fremark: '', fnumber: '', fname: '', fdescription: '', fpurfbillno: '', salKhddh: ''
      })
    },
    // 删除行
    delHang() {
      const fid = this.tableData[this.indexSelf].fentryId
      this.delArr.push(fid)
      this.tableData.splice(this.indexSelf, 1)
    }
  }
}
</script>
<style>
.proceeDetail .el-table .el-input-number .el-input {
    width: 75px;
}
</style>
<style lang="scss" scoped>
.tabPosit {
  padding: 5px;
  box-shadow: 0 0 2px #aaa;
  position: absolute;
  top: 3.5vh;
  left: 0;
  background-color: rgba(255, 255, 255, 1);
  z-index: 99999!important;
}
.tabPosit1 {
  padding: 5px;
  box-shadow: 0 0 2px #aaa;
  position: absolute;
  top: -25.69vh;
  left:0;
  background-color: rgba(255, 255, 255, 1);
  z-index: 9999;
}
.proceeDetail {
  @include listBom;
  .header{
    margin-top: 10px;
    .header-name{
      span {
        width: 100px;
        margin-right: 10px;
        text-align: right;
      }
    }
  }
  .el-table{
    &::v-deep .el-input-number .el-input__inner{
      padding: 0;
      width: 75px;
      height: 30px;
    }
    &::v-deep .el-input-number .el-input{
      width: 75px;
      height: 35px;
      line-height: 35px;
    }
    &::v-deep .el-input-number--mini{
      width: 75px;
    }
    &::v-deep .el-input-number__increase{
      display: none;
    }
    &::v-deep .el-input-number__decrease{
      display: none;
    }
    &::v-deep .el-table__footer-wrapper tbody td{
      background: #fdf6ec!important;
    }
  }
  .el-input::v-deep .el-input__inner {
    height: 30px;
    line-height: 30px;
  }
  .el-form {
    display: flex;
    flex-wrap: wrap;

    .el-form-item {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      height: 35px;
      width: 268px;
      margin-bottom: 3px;
      //&::v-deep .el-input--mini .el-input__inner{
      //  height: 22px;
      //}
      .btnType {
        margin-right: 20px;
      }

      .el-date-editor.el-input {
        width: 100% !important;
      }

      .el-select {
        width: 100%;
      }
    }
  }
}
</style>
